<template>
  <view class="order-detail-page">
    <view class="detail-header">
      <text class="title">订单详情</text>
    </view>

    <!-- 商品列表 -->
    <view class="goods-list">
      <view
        v-for="item in orderDetails"
        :key="item.detailId"
        class="goods-item"
      >
        <image :src="item.productImage" class="goods-image" mode="aspectFill" />
        <view class="goods-info">
          <text class="goods-name">{{ item.productName }}</text>
          <text class="goods-price">¥{{ item.unitPrice.toFixed(2) }}</text>
          <text class="goods-quantity">× {{ item.quantity }}</text>
        </view>
        <text class="goods-subtotal">¥{{ item.subtotal.toFixed(2) }}</text>
      </view>
    </view>

    <!-- 订单信息 -->
    <view class="order-summary">
      <view class="summary-row">
        <text>商品总额：</text>
        <text>¥{{ totalAmount.toFixed(2) }}</text>
      </view>
      <view class="summary-row">
        <text>运费：</text>
        <text>¥{{ freight.toFixed(2) }}</text>
      </view>
      <view class="summary-row total">
        <text>实付金额：</text>
        <text>¥{{ (totalAmount + freight).toFixed(2) }}</text>
      </view>
    </view>

  </view>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import { getOrderDetail } from '@/api/Productapi.js';
import userManager from '@/common/utils/user.js';
import { onLoad, onShow, onReady } from '@dcloudio/uni-app';
import { orderCache } from '@/common/utils/orderCache.js';

// 路由参数通过 onLoad 获取
let orderId = '';

// 使用 UniApp 的 onLoad 生命周期
onLoad((query) => {
  orderId = query.orderId;
  if (!orderId) {
    uni.showToast({ title: '订单ID缺失', icon: 'none' });
    uni.navigateBack();
  }
});

const orderDetails = ref([]);
const orderInfo = ref(null); // 后续可从订单列表缓存或额外接口获取，此处简化
// 计算总金额
const totalAmount = computed(() => {
  return orderDetails.value.reduce((sum, item) => sum + item.subtotal, 0);
});
const freight = ref(10); // 实际项目中应从订单主表获取，这里暂定为0

// 状态映射（复用）
const statusMap = {
  0: '待付款',
  1: '待收货',
  2: '待评价',
  3: '已退款'
};

const getStatusText = (status) => {
  return statusMap[status] || '未知状态';
};

// 时间格式化
const formatTime = (time) => {
  if (!time) return '—';
  const date = new Date(time);
  if (isNaN(date.getTime())) return '—';
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hour = String(date.getHours()).padStart(2, '0');
  const minute = String(date.getMinutes()).padStart(2, '0');
  return `${year}-${month}-${day} ${hour}:${minute}`;
};

onMounted(async () => {
  if (!orderId) return;
	 
  // // 优先从缓存读取主订单信息
  // const cachedOrder = orderCache[orderId];
  // if (cachedOrder) {
  //   orderInfo.value = cachedOrder;
  //   freight.value = cachedOrder.freight || 0;
  //   // 可选：删除缓存，避免内存泄漏（用户返回后不再需要）
  //   // delete globalOrderCache[orderId];
  // } else {
  //   // 缓存不存在，则调用接口获取主订单（你可能需要补充这个接口）
  //   // 暂时用占位逻辑
  //   console.warn('主订单缓存未命中，建议实现 getOrderById 接口');
  //   // 示例：const mainOrder = await getOrderById(orderId);
  //   // orderInfo.value = mainOrder;
  //   // freight.value = mainOrder.freight || 0;
  // }

  // 加载商品明细（子订单）
  uni.showLoading({ title: '加载中...' });
  const details = await getOrderDetail(orderId);
  uni.hideLoading();

  if (details) {
    orderDetails.value = details;
  }
});
</script>

<style scoped>
.order-detail-page {
  padding: 20rpx;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.detail-header {
  text-align: center;
  margin-bottom: 30rpx;
}

.title {
  font-size: 36rpx;
  font-weight: bold;
}

.goods-list {
  background: #fff;
  border-radius: 12rpx;
  padding: 20rpx;
  margin-bottom: 20rpx;
}

.goods-item {
  display: flex;
  align-items: center;
  padding: 20rpx 0;
  border-bottom: 1rpx solid #eee;
}

.goods-item:last-child {
  border-bottom: none;
}

.goods-image {
  width: 160rpx;
  height: 160rpx;
  border-radius: 8rpx;
  margin-right: 20rpx;
}

.goods-info {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.goods-name {
  font-size: 28rpx;
  margin-bottom: 10rpx;
  color: #333;
}

.goods-price {
  color: #e54d42;
  font-size: 26rpx;
}

.goods-quantity {
  color: #999;
  font-size: 24rpx;
  margin-top: 6rpx;
}

.goods-subtotal {
  font-weight: bold;
  color: #e54d42;
  font-size: 28rpx;
}

.order-summary {
  background: #fff;
  border-radius: 12rpx;
  padding: 20rpx;
  margin-bottom: 20rpx;
}

.summary-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 12rpx;
  font-size: 28rpx;
}

.summary-row.total {
  font-weight: bold;
  color: #e54d42;
  margin-top: 10rpx;
  padding-top: 10rpx;
  border-top: 1rpx solid #eee;
}

.section {
  background: #fff;
  border-radius: 12rpx;
  padding: 20rpx;
  margin-bottom: 20rpx;
}

.section-title {
  font-weight: bold;
  font-size: 30rpx;
  margin-bottom: 16rpx;
  display: block;
}

.info-item {
  font-size: 26rpx;
  color: #666;
  margin-bottom: 12rpx;
}
</style>